import 'dart:convert';

import 'package:flutter_provider_demo/data/services/api/api.dart';
import 'package:http/http.dart' as http;
import 'package:flutter_provider_demo/commons/result.dart';
import 'package:flutter_provider_demo/commons/http_client.dart';
import 'package:flutter_provider_demo/data/services/api/models/api_response.dart';
import 'package:flutter_provider_demo/data/services/api/models/auth/login_request.dart';
import 'package:flutter_provider_demo/data/services/api/models/auth/login_response.dart';

class AuthApiClient {
  final HttpClient _client;

  AuthApiClient({HttpClient? client}) : _client = client ?? HttpClient();

  Future<Result<LoginResponse>> login(LoginRequest request) async {
    final response = await _client.post(
      Api.login,
      body: request.toJson(),
    );
    return generateLoginResponse(response);
  }

  Future<Result<LoginResponse>> refreshToken(String? accessToken) async {
    final response = await _client.post(
      Api.refreshToken,
      headers: {
        'Authorization': 'Bearer $accessToken',
      },
      body: {},
    );
    return generateLoginResponse(response);
  }

  Result<LoginResponse> generateLoginResponse(http.Response response) {
    if (response.statusCode == 200) {
      Map<String, dynamic> json = jsonDecode(response.body);
      ApiResponse<LoginResponse?> apiResponse = ApiResponse.fromJson(
          json,
          (data) => data == null
              ? null
              : LoginResponse.fromJson(data as Map<String, dynamic>));
      if (apiResponse.code == 0) {
        return Result.ok(apiResponse.data!);
      } else {
        return Result.error(Exception(apiResponse.message ?? 'Login failed'));
      }
    } else {
      return Result.error(Exception('Login failed'));
    }
  }
}
